#include <iostream>
#include <tuple>
#include <string>
#include <map>

// 用于结构化绑定的自定义结构体
struct Point {
    double x;
    double y;
    double z;
};

// 获取键值对的函数
std::pair<std::string, int> get_name_and_age() {
    return {"张三", 30};
}

// 返回元组的函数
std::tuple<std::string, int, double> get_person_info() {
    return {"李四", 25, 175.5};
}

void demonstrate_structured_bindings() {
    // 1. 绑定到数组
    int array[3] = {1, 2, 3};
    auto [a, b, c] = array;
    std::cout << "  数组绑定: a=" << a << ", b=" << b << ", c=" << c << '\n';
    
    // 2. 绑定到结构体
    Point p{1.0, 2.5, 3.7};
    auto [x, y, z] = p;
    std::cout << "  结构体绑定: x=" << x << ", y=" << y << ", z=" << z << '\n';
    
    // 3. 绑定到pair
    auto [name, age] = get_name_and_age();
    std::cout << "  pair绑定: name=" << name << ", age=" << age << '\n';
    
    // 4. 绑定到tuple
    auto [person_name, person_age, height] = get_person_info();
    std::cout << "  tuple绑定: name=" << person_name 
              << ", age=" << person_age 
              << ", height=" << height << "cm\n";
    
    // 5. 在for循环中使用结构化绑定
    std::map<std::string, int> scores = {
        {"语文", 89},
        {"数学", 95},
        {"英语", 82}
    };
    
    std::cout << "  在for循环中使用结构化绑定:\n";
    for (const auto& [subject, score] : scores) {
        std::cout << "    " << subject << ": " << score << '\n';
    }
    
    // 6. 结构化绑定与引用
    auto& [rx, ry, rz] = p;
    rx = 10.0;  // 修改原始变量
    std::cout << "  通过引用修改: p.x=" << p.x << ", p.y=" << p.y << ", p.z=" << p.z << '\n';
    
    // 7. 结构化绑定与const
    const auto& [cx, cy, cz] = p;
    std::cout << "  使用const引用: cx=" << cx << ", cy=" << cy << ", cz=" << cz << '\n';
    // cx = 20.0;  // 错误! cx是const
} 